#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstdlib>
#include <cassert>
#include <fcntl.h>
#include <unistd.h>
#include <cstring>
using namespace std;

int timeoutConnect (const char* ip, int port, int time) {
    int ret = 0;
    struct sockaddr_in address;
    memset (&address, 0, sizeof(address));
    address.sin_family = AF_INET;
    inet_pton(AF_INET, ip, &address.sin_addr);
    address.sin_port = port;

    int connFd = socket(AF_INET, SOCK_STREAM, 0);
    assert(connFd >= 0);

    struct timeval timeout;
    timeout.tv_sec = time;
    timeout.tv_usec = 0;
    socklen_t len = sizeof(timeout);
    ret = setsockopt(connFd, SOL_SOCKET, SO_SNDTIMEO, &timeout, len);
    assert(ret != -1);

    ret = connect(connFd, (struct sockaddr*)&address, sizeof(address));
    if (ret = -1) {
        if (errno == EINPROGRESS) {
            cout << "connecting timeout, process timeout logic" << endl;
            return -1;
        }
        cout << "error occur when connecting to server" << endl;
        return -1;
    }
    return connFd;
}

int main(int argc, char* argv[]) {
    if (argc <= 2) {
        cout << "Usage: " << argv[0] << " <ip> <port>" << endl;
        return 1;
    }
    const char* ip = argv[1];
    int port = atoi(argv[2]);

    int sockFd = timeoutConnect(ip, port, 10);
    if (sockFd < 0) {
        return 1;
    }
    
    close(sockFd);
    return 0;
}